package com.ruoyi.web.controller.system;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.sso.UserCenterAuthService;
import com.ruoyi.framework.sso.domain.UserCenterLoginResult;
import com.ruoyi.framework.sso.domain.UserCenterTokenResponse;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * 统一用户中心登录接口
 */
@RestController
@RequestMapping("/oauth2")
@Tag(name = "用户授权登录")
public class UserCenterAuthController
{
    private final UserCenterAuthService userCenterAuthService;

    public UserCenterAuthController(UserCenterAuthService userCenterAuthService)
    {
        this.userCenterAuthService = userCenterAuthService;
    }

    private static final String USER_CENTER_AUTH = "用户授权登录";

    /**
     * 使用授权码换取本系统 token
     */
    @Anonymous
    @PostMapping("/codeLogin")
    @Operation(summary = "使用授权码换取本系统 token", tags = USER_CENTER_AUTH)
    public AjaxResult codeLogin(@RequestParam("code") String code,
                                @RequestParam(value = "redirect_uri", required = false) String redirectUri) throws UnsupportedEncodingException {
        String decodedUri = URLDecoder.decode(redirectUri, "UTF-8");
        UserCenterLoginResult loginResult = userCenterAuthService.loginByCode(code, decodedUri);
        UserCenterTokenResponse tokenResponse = loginResult.getTokenResponse();
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, loginResult.getLocalToken());
        ajax.put("accessToken", tokenResponse.getAccessToken());
        ajax.put("refreshToken", tokenResponse.getRefreshToken());
        ajax.put("expiresIn", tokenResponse.getExpiresIn());
        ajax.put("refreshTokenExpiresIn", tokenResponse.getRefreshTokenExpiresIn());
        ajax.put("userInfo", loginResult.getUserInfo());
        return ajax;
    }
}
